import json
from channels.generic.websocket import WebsocketConsumer
from .models import LogsDB


class AutoLogConsumer(WebsocketConsumer):
    old_string = ""

    def connect(self):
        self.accept()

    def disconnect(self, code):
        pass

    def receive(self, text_data=None, bytes_data=None):
        cur_string = ""
        log_set = None
        text_data_json = json.loads(text_data)
        app_name = text_data_json["app_name"]
        operation_no = text_data_json["operation_no"]

        # 用于从日志数据库找到发布单的发布日志
        if text_data_json["env_name"] == "Demo":
            deploy_version = text_data_json["deploy_version"]
            log_set = LogsDB.objects.filter(app_name=app_name, operation_no=operation_no,
                                            operation_type="deploy", deploy_version=deploy_version).order_by("id")

        # 用于从日志数据库找到服务器启停的发布日志
        if text_data_json["deploy_version"] == "Demo":
            env_name = text_data_json["env_name"]
            log_set = LogsDB.objects.filter(app_name=app_name, operation_no=operation_no,
                                            operation_type="operate", deploy_version="Demo", env_name=env_name).order_by("id")

        if log_set is not None:
            for log_item in log_set:
                cur_string += log_item.log_content + "\n"
        if cur_string == self.old_string:
            pass
        else:
            if len(cur_string) > len(self.old_string):
                send_string = cur_string.replace(self.old_string, "")
                self.old_string = cur_string
                self.send(text_data=send_string)
            else:
                pass
